package com.hefan.pay.dao;

import com.hefan.common.orm.dao.BaseDaoImpl;
import com.hefan.pay.bean.PayReqLog;
import org.springframework.stereotype.Repository;

/**
 * Created by lxw on 2016/10/12.
 */
@Repository
public class PayReqLogDao extends BaseDaoImpl<PayReqLog> {

    /**
     * 保存支付请求日志
     * @param orderId
     * @param userId
     * @param reqUrl
     * @param paymentType
     * @param reqParams
     * @param respParams
     * @param status
     * @return
     */
    public PayReqLog savePayReqLog(String orderId, String userId, String reqUrl, int paymentType, String reqParams, String respParams, int status) {
        PayReqLog payReqLog = new PayReqLog();
        payReqLog.setOrderId(orderId);
        payReqLog.setUserId(userId);
        payReqLog.setReqUrl(reqUrl);
        payReqLog.setPaymentType(paymentType);
        payReqLog.setReqParams(reqParams);
        payReqLog.setRespParams(respParams);
        payReqLog.setStatus(status);
        payReqLog.setNotifyStatus(0);
        payReqLog.setNotifyResult("");
        payReqLog.setNotifyParams("");
        return this.save(payReqLog);
    }

    /**
     * 更新支付请求日志中回调通知信息
     * @param orderId
     * @param notifyStatus
     * @param notifyResult
     * @param notifyParams
     * @return
     */
    public int updatePayReqNotifyInfo(String orderId, int notifyStatus,String notifyResult, String notifyParams) {
        String sql = "update pay_req_log set notify_status=?,notify_result=?,notify_params=? where order_id=?";
        return getJdbcTemplate().update(sql, new Object[] {notifyStatus,notifyResult,notifyParams,orderId});
    }

    public int updatePayReqNotifyInfoForAppleStore(String orderId, int notifyStatus,String notifyResult, String notifyParams, String receiptStr, String transactionId) {
        String sql = "update pay_req_log set notify_status=?,notify_result=?,notify_params=?,receipt_str=?,transaction_id=? where order_id=?";
        return getJdbcTemplate().update(sql, new Object[] {notifyStatus,notifyResult,notifyParams,receiptStr,transactionId,orderId});
    }


    /**
     * 检查评估内购receipt_data字符串是否重复
     * @param orderId
     * @param receiptMd5
     * @return
     */
    public int getAppleStoreReceiptCount(String orderId, String receiptMd5) {
        String countSql = "select count(1) from pay_req_log where payment_type=1 AND notify_status=1000 and receipt_str=? and order_id<>?";
        return getJdbcTemplate().queryForObject(countSql,new Object[] {receiptMd5,orderId}, Integer.class);
    }



}
